﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FbKPI.Facade;
using FbKPI.Model;
using FbKPI.Facade.Validator;
using System.Transactions;

namespace FBKPI.Pages
{
    public partial class InputVerificationPage : System.Web.UI.Page
    {
        protected override void OnPreRender(EventArgs e)
        {
            //ViewState["update"] = Session["update"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());

                int KPIAchievementID = Convert.ToInt32(Request.QueryString["KPIAchievement"]);
                KPIAssign.Value = Request.QueryString["KPIAssign"];
                KPI.Value = new KPIAssignFacade().GetKPIAssignByID(Convert.ToInt32(KPIAssign.Value)).KPI.ID.ToString();
                int ID = Convert.ToInt32(KPI.Value);
                hfKpiAssignId.Value = Request.QueryString["KPIAssign"];

                IList<string> Status = new List<string>();
                foreach (KPIStatus x in new KPIStatusFacade().GetAllKPIStatus().ToList())
                {
                    //Status.Add(x.Description);
                    ddl_statusbyverificator.Items.Add(new ListItem(x.Description, x.ID.ToString()));
                }

                ddl_statusbyverificator.Items.Insert(0, new ListItem("---pilih status---", "0"));
                
                if (ID != 0)
                {
                    KPIFacade df = new KPIFacade();
                    KPI KPIs = df.GetKPIByID(ID);

                    if (KPIs != null)
                    {
                        txt_kpidescription.Text = KPIs.Description;
                        hfKpiId.Value = KPIs.ID.ToString();
                        chk_active.Checked = KPIs.isActive;
                        //chk_weightenableflag.Checked = KPIs.WeightEnableFlag;
                        //chk_uomenableflag.Checked = KPIs.UoMEnableFlag;
                        txt_kpigroup.Text = KPIs.GroupKPI == null ? "" : KPIs.GroupKPI.Description;
                        txt_kpicategory.Text = KPIs.CategoryKPI == null ? "" : KPIs.CategoryKPI.Description;
                        txt_kpitype.Text = KPIs.TypeKPI == null ? "" : KPIs.TypeKPI.Description;
                        txt_kpisubtype.Text = KPIs.SubTypeKPI == null ? "" : KPIs.SubTypeKPI.Description;
                        //txt_kpiuom.Text = KPIs.UoM == null ? "" : KPIs.UoM.Description;
                        //txt_kpiuommax.Text = KPIs.UoMDetailMax == null ? "" : KPIs.UoMDetailMax.Description + " || " + KPIs.UoMDetailMax.ListValue;
                        //txt_kpiuommin.Text = KPIs.UoMDetailMin == null ? "" : KPIs.UoMDetailMin.Description + " || " + KPIs.UoMDetailMin.ListValue;
                        //txt_kpiparent.Text = KPIs.KPIParent == null ? "" : KPIs.KPIParent.Description;
                        //txt_kpireplacement.Text = KPIs.KPIReplacement == null ? "" : KPIs.KPIReplacement.Description;
                        txt_kpiyear.Text = KPIs.Year.ToString();
                        txt_weight.Text = KPIs.Weight.ToString();
                        txt_kpiperiode.Text = KPIs.Periode;
                        txt_polarization.Text = KPIs.Polarization;
                        //txt_kpitargetdescription.Text = KPIs.TargetDescription;
                        //txt_kpimanualcalculation.Text = KPIs.ManualCalculation.ToString();
                        //txt_calculationtype.Text = KPIs.KPICalculationType;
                        //txt_replacementdate.Text = KPIs.ReplacementDate == null ? "" : Convert.ToDateTime(KPIs.ReplacementDate).ToShortDateString();
                        //txt_replacementdescription.Text = KPIs.ReplacementDescription;
                        //txt_detailinformation.Text = KPIs.KPIDetailInformation;
                        //txt_strategicobjective.Text = KPIs.KPIStrategicObjective;
                       // txt_uomformat.Value = KPIs.UoM.Format.ToString();
                        //txt_achievementyear.Text = KPIs.Year.ToString();

                        //if (KPIs.UoM.Format == UoMFormat.Month)
                        //{
                        //    txt_realizationmonth.Visible = true;
                        //    txt_realization.Visible = false;
                        //}
                        //else
                        //{
                        //    txt_realizationmonth.Visible = false;
                        //    txt_realization.Visible = true;
                        //}
                        string statusVerificator = string.Empty;
                        KPIAchievementFacade acvfacade = new KPIAchievementFacade();
                        List<KPIAchievement> list = acvfacade.GetListKPIAchievement(Convert.ToInt32(hfKpiAssignId.Value));
                        string statusByUser = "None";
                        if (list.Count > 0)
                        {
                            hfTotalDataAchievment.Value = list.Count.ToString();

                            foreach (KPIAchievement data in list)
                            {
                                statusVerificator = data.StatusByVerificator.ID.ToString();
                                statusByUser = data.StatusByUser.ID.ToString();
                                break;
                            }

                            ddl_statusbyverificator.Items.FindByValue(statusVerificator).Selected = true;
                        }

                        KPIAttachmentFacade attcFacade = new KPIAttachmentFacade();
                        IList<KPIAttachment> listAttc = attcFacade.GetKPIAttachmentByKPIAssign_KpiAssign(Convert.ToInt32(hfKpiAssignId.Value));
                        hfTotalDataAttachment.Value = listAttc.Count.ToString();

                        IList<KPI> listKpiChild = df.GetKPIChilds(KPIs);
                        hfTotalDataKpiChild.Value = listKpiChild.Count.ToString();

                        if (statusByUser == "1")
                            statusByUser = "On Progress";
                        else if (statusByUser == "2")
                            statusByUser = "UnDone";
                        else if (statusByUser == "3")
                            statusByUser = "Done";
                        else
                            statusByUser = "None";

                        lblStatusUser.Text = statusByUser;


                    }

                   
                }

                

                //ddl_statusbyuser.DataSource = Status;
                //ddl_statusbyuser.DataBind();

                //ddl_statusbyverificator.DataSource = Status;
                //ddl_statusbyverificator.DataBind();

                ClearContent();

            }

        }

        protected void SaveAction(object sender, EventArgs e)
        {
            //try
            //{
            //    if (Session["update"].ToString() == ViewState["update"].ToString())
            //    {
            //        if (State.Value == "Wait")
            //        {
            //            KPIAchievement Achievement = new KPIAchievementFacade().GetKPIAchievementDetail(Convert.ToInt32(txt_monthnumber.Value), Convert.ToInt32(txt_achievementyear.Text), Convert.ToInt32(KPIAssign.Value));
            //            if (Achievement != null)
            //            {
            //                Achievement.Notes = txt_remark.Text;
            //                Achievement.Score = txt_score.Text;

            //                if (Achievement.KPIAssign.KPI.UoM.Format == UoMFormat.Month)
            //                    Achievement.Realization = txt_realizationmonth.Text;
            //                else
            //                    Achievement.Realization = txt_realization.Text;

            //                Achievement.StatusByVerificator = new KPIStatusFacade().GetKPIStatusByID(ddl_statusbyverificator.SelectedIndex + 1);
            //                Achievement.LastModifiedBy = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"])).Email;

            //                KPIAchievementFacade af = new KPIAchievementFacade();
            //                KPIAchievementValidator av = new KPIAchievementValidator();

            //                string msg = av.ValidateOnSave(Achievement);
            //                if (msg == "OK")
            //                {
            //                    using (TransactionScope trans = new TransactionScope(TransactionScopeOption.RequiresNew))
            //                    {
            //                        try
            //                        {
            //                            msg = af.Save(Achievement);

            //                            if (!msg.Contains("Success"))
            //                            {
            //                                int x = 0;
            //                                int y = 1;
            //                                int z = y / x;
            //                            }
            //                            else
            //                            {
            //                                //Set All KPI Parents Achivement Score
            //                                //Populate All KPI Parents
            //                                IList<KPI> Parents = null;
            //                                KPI Parent = new KPIFacade().GetKPIByID(Achievement.KPIAssign.KPI.KPIParent == null ? 0 : Achievement.KPIAssign.KPI.KPIParent.ID);

            //                                if (Parent != null)
            //                                {
            //                                    Parents = new List<KPI>();
            //                                    if (Parent.ScoredBySystem)
            //                                        Parents.Add(Parent);

            //                                    if (Parent.KPIParent != null)
            //                                    {
            //                                        while (Parent != null)
            //                                        {
            //                                            Parent = new KPIFacade().GetKPIByID(Parent.KPIParent == null ? 0 : Parent.KPIParent.ID);
            //                                            if (Parent != null)
            //                                            {
            //                                                if (Parent.ScoredBySystem)
            //                                                    Parents.Add(Parent);
            //                                                else
            //                                                    break;
            //                                            }
            //                                        }
            //                                    }
            //                                }

            //                                if (Parents != null)
            //                                {
            //                                    //Get And Fill Achievements for all KPI Parent
            //                                    decimal AchievementScore = 0;
            //                                    decimal AssignScore = 0;
            //                                    decimal ChildScore = 0;
            //                                    decimal ChildMean = 0;
            //                                    decimal ParentScore = 0;

            //                                    foreach (KPI w in Parents)
            //                                    {
            //                                        ParentScore = 0;
            //                                        IList<KPI> Childs = new KPIFacade().GetKPIChilds(w);
            //                                        if (Childs != null && Childs.Count > 0)
            //                                        {
            //                                            ChildScore = 0;
            //                                            foreach (KPI x in Childs)
            //                                            {
            //                                                IList<KPIAssign> ChildAssign = new KPIAssignFacade().GetAllKPIAssignsByKPIID(x.ID);

            //                                                if (ChildAssign != null && ChildAssign.Count > 0)
            //                                                {
            //                                                    foreach (KPIAssign y in ChildAssign)
            //                                                    {
            //                                                        IList<KPIAchievement> ChildAchievements = new KPIAchievementFacade().GetKPIAchievementTable(w.Year, y.ID);

            //                                                        if (ChildAchievements != null && ChildAchievements.Count > 0)
            //                                                        {
            //                                                            foreach (KPIAchievement z in ChildAchievements)
            //                                                            {
            //                                                                if (z != null)
            //                                                                    AchievementScore += (z.Score == null ? 0 : Convert.ToDecimal(z.Score));
            //                                                                else
            //                                                                    AchievementScore += 0;
            //                                                            }
            //                                                            if (ChildAchievements.Where(g => g != null && g.StatusByVerificator != null).Count() == 0)
            //                                                                AssignScore += 0;
            //                                                            else
            //                                                                AssignScore += (AchievementScore / ChildAchievements.Where(g => g != null && g.StatusByVerificator != null).Count());
            //                                                            AchievementScore = 0;
            //                                                        }
            //                                                    }
            //                                                    ChildScore += (AssignScore / ChildAssign.Count);
            //                                                    AssignScore = 0;
            //                                                }
            //                                            }
            //                                            ChildMean = (ChildScore / Childs.Count);
            //                                        }
            //                                        else
            //                                        {
            //                                            IList<KPIAssign> ParentAssign = new KPIAssignFacade().GetAllKPIAssignsByKPIID(w.ID);

            //                                            if (ParentAssign != null && ParentAssign.Count > 0)
            //                                            {
            //                                                foreach (KPIAssign y in ParentAssign)
            //                                                {
            //                                                    IList<KPIAchievement> ParentAchievements = new KPIAchievementFacade().GetKPIAchievementTable(w.Year, y.ID);

            //                                                    if (ParentAchievements != null && ParentAchievements.Count > 0)
            //                                                    {
            //                                                        foreach (KPIAchievement z in ParentAchievements)
            //                                                        {
            //                                                            if (z != null)
            //                                                                AchievementScore += (z.Score == null ? 0 : Convert.ToDecimal(z.Score));
            //                                                            else
            //                                                                AchievementScore += 0;
            //                                                        }
            //                                                        if (ParentAchievements.Where(g => g != null && g.StatusByVerificator != null).Count() == 0)
            //                                                            AssignScore += 0;
            //                                                        else
            //                                                            AssignScore += (AchievementScore / ParentAchievements.Where(g => g != null && g.StatusByVerificator != null).Count());
            //                                                        AchievementScore = 0;
            //                                                    }
            //                                                }
            //                                                ChildMean += (AssignScore / ParentAssign.Count);
            //                                                AssignScore = 0;
            //                                            }
            //                                        }
            //                                        ParentScore = ChildMean;
            //                                        ChildMean = 0;

            //                                        //save each kpi parent achievements
            //                                        IList<KPIAssign> wAssign = new KPIAssignFacade().GetAllKPIAssignsByKPIID(w.ID);

            //                                        if (wAssign != null && wAssign.Count > 0)
            //                                        {
            //                                            foreach (KPIAssign y in wAssign)
            //                                            {
            //                                                IList<KPIAchievement> ParentAchievements = new KPIAchievementFacade().GetKPIAchievementTable(w.Year, y.ID);

            //                                                if (ParentAchievements != null && ParentAchievements.Where(g=> g!=null).Count() > 0)
            //                                                {
            //                                                    foreach (KPIAchievement z in ParentAchievements)
            //                                                    {
            //                                                        if (z != null)
            //                                                        {
            //                                                            z.LastModifiedBy = Achievement.LastModifiedBy;
            //                                                            z.Score = ParentScore.ToString("0.00");
            //                                                            z.Realization = ParentScore.ToString("0.00");
            //                                                            z.Month = DateTime.Now.Month;
            //                                                            z.Year = Achievement.Year;
            //                                                            z.Notes = "Scored by System";

            //                                                            msg = af.Save(z);

            //                                                            if (!msg.Contains("Success"))
            //                                                            {
            //                                                                int o = 0;
            //                                                                int p = 1;
            //                                                                int q = p / o;
            //                                                            }
            //                                                        }
            //                                                    }
            //                                                }
            //                                                else
            //                                                {
            //                                                    KPIAchievement Ach = new KPIAchievement() { 
            //                                                        ID = 0,
            //                                                        KPIAssign = y,
            //                                                        Month = DateTime.Now.Month,
            //                                                        Year = w.Year,
            //                                                        Realization = ParentScore.ToString("0.00"),
            //                                                        Score = ParentScore.ToString("0.00"),
            //                                                        StatusByUser = new KPIStatusFacade().GetAllKPIStatus().Where(g=> g.Description == "Done" && g.isActive).FirstOrDefault(),
            //                                                        StatusByVerificator = new KPIStatusFacade().GetAllKPIStatus().Where(g => g.Description =="Done" && g.isActive).FirstOrDefault(),
            //                                                        isLocked = false,
            //                                                        Notes = "Scored by System",
            //                                                        isActive = true,
            //                                                        CreateBy = Achievement.LastModifiedBy
            //                                                    };

            //                                                    msg = af.Save(Ach);

            //                                                    if (!msg.Contains("Success"))
            //                                                    {
            //                                                        int o = 0;
            //                                                        int p = 1;
            //                                                        int q = p / o;
            //                                                    }
            //                                                }
            //                                            }
            //                                        }
            //                                    }
            //                                    //--------------------------------------------
            //                                }
            //                                //------------------------------------------------
            //                                Response.Write("<script>alert('" + msg + "');</script>");
            //                                ClearContent();
            //                            }
            //                        }
            //                        catch (Exception ex)
            //                        {
            //                            Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //                            logwriter.WriteLog(msg, ex.StackTrace.ToString());
            //                            Response.Write("<script>alert('" + msg + "');</script>");
            //                        }
            //                        finally
            //                        {
            //                            trans.Complete();
            //                            trans.Dispose();
            //                        }
            //                    }

            //                }
            //                else
            //                {
            //                    Response.Write("<script>alert('" + msg + "');</script>");
            //                }
            //            }
            //            Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //    logwriter.WriteLog(ex.Message.ToString(), ex.StackTrace.ToString());
            //    Response.Redirect("../login.aspx");
            //}
        }

        protected void ReleaseAction(object sender, EventArgs e)
        {
            //try
            //{
                //if (Session["update"].ToString() == ViewState["update"].ToString())
                //{
                //    if (State.Value == "Wait")
                //    {
                      
                           
                //    }
                //}

            //           KPIAchievement Achievement = new KPIAchievementFacade().GetKPIAchievementDetail(Convert.ToInt32(txt_monthnumber.Value), Convert.ToInt32(txt_achievementyear.Text), Convert.ToInt32(KPIAssign.Value));
            //           if (Achievement != null)
            //           {
            //               Achievement.Notes = txt_remark.Text;
            //               Achievement.Score = txt_score.Text;

            //               if (Achievement.KPIAssign.KPI.UoM.Format == UoMFormat.Month)
            //                   Achievement.Realization = txt_realizationmonth.Text;
            //               else
            //                   Achievement.Realization = txt_realization.Text;

            //               Achievement.StatusByVerificator = new KPIStatusFacade().GetKPIStatusByID(ddl_statusbyverificator.SelectedIndex + 1);
            //               Achievement.LastModifiedBy = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(Request.QueryString["User"])).Email;

            //               KPIAchievementFacade af = new KPIAchievementFacade();

            //               string msg = af.UpdateRelease(Achievement);

            //               Response.Write("<script>alert('" + msg + "');</script>");
            //               ClearContent();
            //           }
            //}
            //catch (Exception ex)
            //{
            //    Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
            //    logwriter.WriteLog(ex.Message.ToString(), ex.StackTrace.ToString());
            //    Response.Redirect("../login.aspx");
            //}
        }
       
        private void ClearContent()
        {
            //State.Value = string.Empty;
            //txt_month.Text = string.Empty;
            //txt_monthnumber.Value = string.Empty;
            //txt_realization.Text = string.Empty;
            //txt_realizationmonth.Text = string.Empty;
            //ddl_statusbyuser.SelectedIndex = 0;
            //ddl_statusbyverificator.SelectedIndex = 0;
            //txt_score.Text = string.Empty;
            //txt_remark.Text = string.Empty;
        }
    }
}